<?php
require(CP_PATH . 'lib/common.function.php');
require(CP_PATH . 'ext/template_ext.php');
//获取微秒时间
function form_time()
{
    list($s1, $s2) = explode(' ', microtime());
    return (float) sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
}
//调试运行时间和占用内存
function debug($flag = 'system', $end = false)
{
    static $arr = array();
    if (!$end) {
        $arr[$flag] = microtime(true);
    } else if ($end && isset($arr[$flag])) {
        echo '<p>' . $flag . ': runtime:' . round((microtime(true) - $arr[$flag]), 6) . '    memory_usage:' . memory_get_usage() / 1000 . 'KB</p>';
    }
}
//保存配置
function save_config($app, $new_config = array())
{
    if (!is_file($app)) {
        $file = ROOT_PATH . 'apps/' . $app . '/config.php';
    } else {
        $file = $app;
    }
    if (is_file($file)) {
        $config = require($file);
        $config = array_merge($config, $new_config);
    } else {
        $config = $new_config;
    }
    $content = var_export($config, true);
    $content = str_replace("_PATH' => '" . addslashes(ROOT_PATH), "_PATH' => ROOT_PATH . '", $content);
    if (file_put_contents($file, "<?php \r\nreturn " . $content . ';')) {
        return true;
    }
    return false;
}
//复制文件夹
function copy_dir($src, $dst, $del = false)
{
    if ($del && file_exists($dst)) {
        return del_dir($dst);
    }
    if (is_dir($src)) {
        @mkdir($dst, 0777, true);
        $files = scandir($src);
        foreach ($files as $file) {
            if ($file != "." && $file != "..")
                copy_dir("$src/$file", "$dst/$file");
        }
    } else if (file_exists($src))
        copy($src, $dst);
}
//判断ajax提交
function is_ajax()
{
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
        return true;
    if (isset($_POST['ajax']) || isset($_GET['ajax']))
        return true;
    return false;
}
//随机数
function getcode($length = 5, $mode = 0)
{
    switch ($mode) {
        case '1':
            $str = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()';
            break;
        case '2':
            $str = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ-=[]\',./';
            break;
        case '3':
            $str = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ<>?:"|{}_+';
            break;
        default:
            $str = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            break;
    }
    $result = '';
    $l = strlen($str) - 1;
    $num = 0;
    for ($i = 0; $i < $length; $i++) {
        $num = rand(0, $l);
        $a = $str[$num];
        $result = $result . $a;
    }
    return $result;
}
//设置cookie
function set_cookie($key, $value = '', $dir, $time = 0)
{
    $config = config('APP');
    $time = $time > 0 ? $time : 0;
    return setcookie($config['COOKIE_PREFIX'].$key, cp_encode($value, $config['SAFE_KEY']), time()+$time, $dir);
}
//获取cookie
function get_cookie($key)
{
    $config = config('APP');
    return isset($_COOKIE[$config['COOKIE_PREFIX'].$key]) ? cp_decode($_COOKIE[$config['COOKIE_PREFIX'].$key], $config['SAFE_KEY']) : '';
}
//数组排序
function array_order($array, $key, $type = 'asc', $reset = true)
{
    if (empty($array) || !is_array($array)) {
        return $array;
    }
    foreach ($array as $k => $v) {
        $keysvalue[$k] = $v[$key];
    }
    if ($type == 'asc') {
        asort($keysvalue);
    } else {
        arsort($keysvalue);
    }
    $i = 0;
    foreach ($keysvalue as $k => $v) {
        $i++;
        if ($reset) {
            $new_array[$i] = $array[$k];
        } else {
            $new_array[$key] = $array[$k];
        }
    }
    return $new_array;
}
//清除html
function clear_html($string)
{
    $string = strip_tags($string);
    $string = preg_replace('/\n/is', '', $string);
    $string = preg_replace('/ |　/is', '', $string);
    $string = preg_replace('/&nbsp;/is', '', $string);
    preg_match_all("/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/", $string, $t_string);
    $string = join('', $t_string[0]);
    return $string;
}
//api接口方法
function hook_api($action, $params = array())
{
    $app = APP_NAME;
    $cacheFile = ROOT_PATH . 'cache/app_cache/' . 'app_list.php';
    $file = @file_get_contents($cacheFile);
    if (empty($file)) {
        cache_api();
        $file = @file_get_contents($cacheFile);
    }
    if (empty($file)) {
        return;
    }
    $list = unserialize($file);
    if (!empty($list)) {
        foreach ($list as $key => $value) {
            if (in_array($action, $value)) {
                $api[$key] = api($key, $action, $params);
            }
        }
    }
    config('_APP_NAME', $app);
    return $api;
}
//缓存API列表
function cache_api()
{
    $list = getApps();
    $dir = ROOT_PATH . 'cache/app_cache/';
    $cacheFile = $dir . 'app_list.php';
    if (!file_exists($dir)) {
        if (!@mkdir($dir, true)) {
            throw new Exception($dir . ' 缓存目录无法创建，请检查目录权限！', 404);
        }
    }
    if (!empty($list)) {
        foreach ($list as $app) {
            $className = $app . 'Api';
            $file = ROOT_PATH . 'apps/' . $app . '/' . $className . '.php';
            if (!is_file($file)) {
                continue;
            }
            if(!class_exists($className)){
                require_once($file);
            }
            if(!class_exists($className)){
                continue;
            }
            $listArray[$app] = get_class_methods($app . 'Api');
        }
        $html = serialize($listArray);
        if (!@file_put_contents($cacheFile, $html)) {
            throw new Exception('APP缓存文件无法写入，请检查目录权限！', 404);
        }
    }
}
//获取文件或文件大小
function dir_size($directoty)
{
    $dir_size = 0;
    if ($dir_handle = @opendir($directoty)) {
        while ($filename = readdir($dir_handle)) {
            $subFile = $directoty . DIRECTORY_SEPARATOR . $filename;
            if ($filename == '.' || $filename == '..') {
                continue;
            } elseif (is_dir($subFile)) {
                $dir_size += dir_size($subFile);
            } elseif (is_file($subFile)) {
                $dir_size += filesize($subFile);
            }
        }
        closedir($dir_handle);
    }
    return ($dir_size);
}
//时间格式化
function format_time($time, $format)
{
    return date($format, $time);
}
//判断为空
function is_empty($info, $msg)
{
    if (empty($info)) {
        return $msg;
    } else {
        return $info;
    }
}
